package com.tron.xml;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;
import java.io.File;

public class SaxStart {
    public static void main(String[] args) throws Exception {
        final File file = new File("src/main/java/com/tron/xml/tron.xml");
        parseXml(file, new TronHandler());
    }

    public static void parseXml(File file,TronHandler tronHandler) throws Exception {
        final SAXParserFactory saxParserFactory = SAXParserFactory.newInstance();
        final SAXParser saxParser = saxParserFactory.newSAXParser();
        saxParser.parse(file,tronHandler);
    }

    public static class TronHandler extends DefaultHandler{

        @Override
        public void startDocument() throws SAXException {
            System.out.println("解析xml开始");
        }

        @Override
        public void endDocument() throws SAXException {
            System.out.println("\n解析xml结束");
        }

        @Override
        public void startElement(String uri, String localName, String qName, Attributes attributes) throws SAXException {
            // 前缀
            System.out.printf("<%s",qName);
            // 属性
            if (null != attributes) {
                for (int i = 0; i < attributes.getLength(); i++) {
                    System.out.printf(" %s=\"%s\"",attributes.getQName(i),attributes.getValue(i));
                }
            }
            // 后缀
            System.out.printf(">");
        }

        @Override
        public void endElement(String uri, String localName, String qName) throws SAXException {
            System.out.printf("</%s>",qName);
        }

        @Override
        public void characters(char[] ch, int start, int length) throws SAXException {
            System.out.printf("%s",new String(ch, start, length));
        }


    }

}
